import React, {useEffect, useState} from 'react';
import { Form, Button, DatePicker,TreeSelect,Upload,Input, Modal,Row,message, Col,Select} from 'antd';
import { connect } from 'umi';
import moment from 'moment';
import {UploadOutlined} from '@ant-design/icons';
import {getUploadUrl} from '@/utils/upload';
import SelectUserModal from "@/pages/components/SelectUserModal";
import { SearchOutlined } from '@ant-design/icons';
import {getShiftFrequency} from '../../service';

const FormItem = Form.Item;
const { TextArea } = Input;
const {Option} = Select;

const formLayout = {
  labelCol: { span: 7 },
};

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

let uploadedFiles = [];
const ShiftAddForm = (props) => {
  const { onSubmit, onCancel, loading,visible,currentUser,record,title,global={}} = props;
  const {options = {}} = global;
  const {jobLevel = []} = options;
  const [form] = Form.useForm();
  const [fileUploadUrls,setFileUploadUrls] = useState([]);
  const [fileName, setFileName] = useState(null);
  const [userModalVisible, setUserModalVisible] = useState(false);
  const [info, setInfo] = useState({});
  const [rankMap,setRankMap] = useState({});

  const fileList = {
    name: 'file',
    multiple: true,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: uploadedFiles,
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls,res.file.response ]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1){
        urls.splice(index, 1);
        setFileUploadUrls(urls);
      }
    },
  };

  useEffect(() => {
    if(currentUser){
      if(record && visible){
        setInfo({oid:record.beShiftOid,name:record.beShiftName});
        getShiftRank(moment(record.shiftDate).format('YYYY-MM-DD'),currentUser.id,record.beShiftOid);
        form.setFieldsValue({...record,shiftDate:moment(record.shiftDate)});
        setFileUploadUrls(record.fileUrl.split(','));
        if(record.fileUrl){
          let fileList = record.fileUrl.split(',');
          fileList.forEach((item,index) =>{
            uploadedFiles.push({
              uid: index,
              name: item.split('----')[1],
              status: 'done',
              url: item,
            })
          });
        }
      }else{
        form.setFieldsValue({...currentUser,shiftCode:currentUser.usercode,shiftOrgName:currentUser.orgname,
          shiftName:currentUser.name,shiftUnitName:currentUser.department,shiftJobName:currentUser.jobname
        });
      }
    }
  }, [visible]);

  const getShiftRank = (dateStr,id,oid) => {
    if(oid){
      const data = {
        shiftDate:dateStr,
        shiftOid:id,
        beShiftOid:oid
      };
      getShiftFrequency(data).then(res => {
        setRankMap(res);
      });
    }else{
      message.warning("请先选择被调班人信息！");
    }
  };

  const onFormCancel = () => {
    form.resetFields();
    onCancel();
    setInfo({});
    uploadedFiles = [];
    setFileUploadUrls([]);
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    form.resetFields();
    onSubmit({
      ...fieldsValue,
      beShiftOid:info.oid,
      shiftOid:currentUser.id,
      fileUrlList:fileUploadUrls,
      id:record && record.id
    });
    setInfo({});
    uploadedFiles = [];
    setFileUploadUrls([]);
  };

  const confirmSelectUser = (usersInfo) =>{
    if (usersInfo.length>0){
      let userInfo = usersInfo[0];
      userInfo.jobLevel = userInfo.jobLevelId ? jobLevel.find(item => item.id===userInfo.jobLevelId)?.name : '';
      let data = {...info, ...userInfo};
      setInfo(data);
      form.setFieldsValue({
        beShiftName:data.name,
        beShiftCode:data.code,
        beShiftOrgName:data.orgname,
        beShiftUnitName:data.unitname,
        beShiftJobName:data.jobname
      });
      setUserModalVisible(false);
    }else {
      message.error('请选择人员!')
    }
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="shiftCode" label="申请人工号">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="shiftName" label="申请人">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="shiftOrgName" label="公司" >
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="shiftUnitName" label="部门" >
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="shiftJobName" label="岗位">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}></Col>
          <Col {...colStyle}>
            <Form.Item label="被调班人" name='beShiftName' rules={[{required: true, message: '请选择人员！'}]}>
              <Input.Group compact size="large">
                <Input style={{ width: '80%',height: '32px', fontSize:'14px', background: '#ffffff' }} placeholder="选择人员" value={info ? info.name : ''} disabled={true}/>
                <Button style={{ width: '20%' }} icon={<SearchOutlined/>} onClick={()=>setUserModalVisible(true)}/>
              </Input.Group>
            </Form.Item>
          </Col>
          <Col {...colStyle}>
            <FormItem name="beShiftCode" label="被调班人工号">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="beShiftOrgName" label="被调班人公司" >
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="beShiftUnitName" label="被调班人部门" >
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="beShiftJobName" label="被调班人岗位">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}></Col>
          <Col {...colStyle}>
            <FormItem name="shiftDate" label="调班时间" rules={[{required: true, message: '调班时间不能为空'}]}>
              <DatePicker disabled={!info.hasOwnProperty("oid")} placeholder="请选择调班时间" className='widthStyle' onChange={(date,dateStr) => getShiftRank(dateStr,currentUser.id,info.oid)}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="frequency" label="调班人班次" rules={[{required: true, message: '调班人班次不能为空'}]}>
              <Select placeholder="请选择调班班次">
                {rankMap.frequencyList && rankMap.frequencyList.map((item, index) => {
                  return (
                    <Option value={`${item.id}`} key={index}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="beFrequency" label="被调班人班次" rules={[{required: true, message: '被调班人班次不能为空'}]}>
              <Select placeholder="请选择被调班人班次">
                {rankMap.beFrequencyList && rankMap.beFrequencyList.map((item, index) => {
                  return (
                    <Option value={`${item.id}`} key={index}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="fileUrl" label="上传附件">
              <Upload {...fileList}>
                <Button>
                  <UploadOutlined/> 点击上传附件
                </Button>
              </Upload>
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem name="reason" labelCol={{span: 2}} label="原因说明" rules={[{required: true, message: '原因说明不能为空'}]}>
              <TextArea rows={4} className='widthStyle'/>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
          <Button type="primary" onClick={() => handleSubmit()} loading={loading}>提交</Button>
      </>
    )
  };

  return (
    <Modal
      maskClosable={false}
      width={1280}
      destroyOnClose
      centered
      title={`调班`+title}
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
      <SelectUserModal
        visible={userModalVisible}
        handleOk={confirmSelectUser}
        handleCancel={()=>setUserModalVisible(false)}
      />
    </Modal>
  )
};

export default connect(({user,global}) => ({
  currentUser: user.currentUser,
  global
}))(ShiftAddForm)
